﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YArchitech.LIB.YJKControls;
using YJKDataBase;

namespace YJKArchiFormat
{
	public partial class DlgAddStandardRoom : System.Windows.Forms.Form
	{
		public DlgAddStandardRoom(IDlgBase main)
		{
			this.mForm = main;
			this.InitializeComponent();
			if (this.mForm.CurrentSubject != null)
			{
				if (this.mForm.CurrentCategory != null)
				{
					this.cbxCategory.Items.Add(this.mForm.CurrentCategory);
					this.cbxCategory.SelectedIndex = 0;
					return;
				}
				this.cbxCategory.Items.Add(this.mForm.CurrentSubject);
				this.cbxCategory.SelectedIndex = 0;
			}
		}

		private void btnAdd_Click(object sender, EventArgs e)
		{
			this.cmdAddRoom((DbCategory)this.cbxCategory.SelectedItem);
			base.Close();
		}

		private static View3D Get3DView(Autodesk.Revit.DB.Document doc)
		{
			View3D result = null;
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc);
			filteredElementCollector.OfClass(typeof(View3D));
			foreach (Element element in filteredElementCollector.ToElements())
			{
				if (element.Name == "{3D}")
				{
					result = (element as View3D);
					break;
				}
			}
			return result;
		}

		private void cmdAddRoom(DbCategory category)
		{
			if (this.tbxPath.Text == "")
			{
				YJKMessageBox.Show("路径为空!");
				return;
			}
			FileInfo fileInfo = new FileInfo(this.tbxPath.Text).CopyTo(Path.GetTempPath() + this.tbxName.Text + ".rvt", true);
			DbStandardRoom dbStandardRoom = new DbStandardRoom(this.tbxName.Text, fileInfo.FullName);
			dbStandardRoom.DbObject.Image = this.pbxView.Image;
			dbStandardRoom.DbObject.SetDate(DateTime.Now);
			dbStandardRoom.DbObject.Version = this.mForm.UiApp.Application.VersionNumber;
			dbStandardRoom.DbObject.Description = this.rtxDescription.Text;
			try
			{
				category.AddObject(dbStandardRoom.DbObject, dbStandardRoom.File);
				this.mForm.LvFamily.LargeImageList.Images.Add(dbStandardRoom.DbObject.Name, dbStandardRoom.DbObject.Image);
				this.mForm.LvFamily.SmallImageList.Images.Add(dbStandardRoom.DbObject.Name, dbStandardRoom.DbObject.Image);
				ListViewItem listViewItem = new ListViewItem();
				listViewItem.Text = dbStandardRoom.DbObject.Name;
				listViewItem.Tag = dbStandardRoom.DbObject;
				listViewItem.ImageKey = dbStandardRoom.DbObject.Name;
				ListViewItem.ListViewSubItem listViewSubItem = new ListViewItem.ListViewSubItem();
				listViewSubItem.Text = dbStandardRoom.DbObject.Version;
				listViewItem.SubItems.Add(listViewSubItem);
				ListViewItem.ListViewSubItem listViewSubItem2 = new ListViewItem.ListViewSubItem();
				listViewSubItem2.Text = dbStandardRoom.DbObject.Date.ToString();
				listViewItem.SubItems.Add(listViewSubItem2);
				ListViewItem.ListViewSubItem listViewSubItem3 = new ListViewItem.ListViewSubItem();
				listViewSubItem3.Text = category.Name;
				listViewItem.SubItems.Add(listViewSubItem3);
				ListViewItem.ListViewSubItem listViewSubItem4 = new ListViewItem.ListViewSubItem();
				listViewSubItem4.Text = dbStandardRoom.DbObject.Description;
				listViewItem.SubItems.Add(listViewSubItem4);
				this.mForm.LvFamily.Items.Add(listViewItem);
			}
			catch (Exception ex)
			{
				YJKMessageBox.Show(ex.Message);
			}
			finally
			{
				fileInfo.Delete();
			}
		}

		private void btnOpen_Click(object sender, EventArgs e)
		{
			this.ofd.Filter = "项目文件|*.rvt";
			this.ofd.RestoreDirectory = true;
			this.ofd.Multiselect = true;
			this.ofd.FilterIndex = 1;
			while (this.ofd.ShowDialog() == DialogResult.OK)
			{
				if (this.ofd.FileName.IndexOf(".rvt") == -1)
				{
					YJKMessageBox.Show("不是有效的项目文件");
				}
				else
				{
					try
					{
						this.btnAdd.Enabled = true;
						this.ofd.FileName.LastIndexOf("\\");
						this.tbxPath.Text = this.ofd.FileName;
						FileInfo fileInfo = new FileInfo(this.ofd.FileNames[0]);
						int length = fileInfo.Name.LastIndexOf(".");
						this.tbxName.Text = fileInfo.Name.Substring(0, length);
						if (this.ofd.FileNames.Count<string>() > 1)
						{
							this.isMulti = true;
							for (int i = 1; i < this.ofd.FileNames.Count<string>(); i++)
							{
								FileInfo fileInfo2 = new FileInfo(this.ofd.FileNames[i]);
								int length2 = fileInfo2.Name.LastIndexOf(".");
								this.tbxName.Text = this.tbxName.Text + ";" + fileInfo2.Name.Substring(0, length2);
							}
						}
						if (!this.GetLargeImage(this.mForm.UiApp, this.tbxPath.Text, this.pbxView))
						{
							this.tbxPath.Text = "";
							this.tbxName.Text = "";
						}
						break;
					}
					catch (Exception)
					{
						break;
					}
				}
			}
		}

		public static XYZ RotateTo(XYZ List, double angle, XYZ axis)
		{
			Transform transform = RevitVersionFuncs.CreateRotationAtPoint(axis, angle, new XYZ(0.0, 0.0, 0.0));
			return DlgAddStandardRoom.TransformPoint(List, transform);
		}

		public static XYZ TransformPoint(XYZ point, Transform transform)
		{
			double x = point.X;
			double y = point.Y;
			double z = point.Z;
			XYZ xyz = transform.get_Basis(0);
			XYZ xyz2 = transform.get_Basis(1);
			XYZ xyz3 = transform.get_Basis(2);
			XYZ origin = transform.Origin;
			double num = x * xyz.X + y * xyz2.X + z * xyz3.X + origin.X;
			double num2 = x * xyz.Y + y * xyz2.Y + z * xyz3.Y + origin.Y;
			double num3 = x * xyz.Z + y * xyz2.Z + z * xyz3.Z + origin.Z;
			return new XYZ(num, num2, num3);
		}

		public bool GetLargeImage(UIApplication uiApp, string docFillPath, PictureBox pbx)
		{
			Document document = uiApp.ActiveUIDocument.Document;
			Document document2 = null;
			try
			{
				document2 = uiApp.Application.OpenDocumentFile(docFillPath);
			}
			catch (Exception)
			{
				YJKMessageBox.Show("所选文件中存在更高版本的Revit文件。");
				return false;
			}
			this.m_Option = new ImageExportOptions();
            this.m_Option.FitDirection = (FitDirectionType)0;
            this.m_Option.HLRandWFViewsFileType = (ImageFileType)1;
            this.m_Option.ImageResolution = (ImageResolution)3;
			this.m_Option.ShouldCreateWebSite = false;
            this.m_Option.ExportRange = (ExportRange)2;
            this.m_Option.ZoomType = (ZoomFitType)0;
			this.m_Option.ViewName = "preview";
			ElementId elementId = null;
			string text = "";
			FilteredElementIterator elementIterator = new FilteredElementCollector(document2).OfClass(typeof(Autodesk.Revit.DB.View)).GetElementIterator();
			elementIterator.Reset();
			while (elementIterator.MoveNext())
			{
				Element element = elementIterator.Current;
				Autodesk.Revit.DB.View view = element as Autodesk.Revit.DB.View;
				if (view != null && !view.IsTemplate && (int)view.ViewType == 4 && (view.Name.CompareTo("{3D}") == 0 || view.Name.CompareTo("{三维}") == 0))
				{
					View3D view3D = view as View3D;
					XYZ xyz = new XYZ(-1.0, 1.0, -1.0);
					XYZ xyz2 = xyz * 10.0;
					XYZ xyz3 = xyz;
					XYZ xyz4 = new XYZ(xyz.X, xyz.Y, 0.0);
					xyz4 = DlgAddStandardRoom.RotateTo(xyz4, -Math.PI*.5, XYZ.BasisZ);
					XYZ xyz5 = DlgAddStandardRoom.RotateTo(xyz3, Math.PI*.5, xyz4);
					ViewOrientation3D orientation = new ViewOrientation3D(xyz2, xyz5, xyz3);
					view3D.SetOrientation(orientation);
					Transaction transaction = new Transaction(document2);
					transaction.Start("set display style");
                    view3D.DisplayStyle = (DisplayStyle)8;
					view3D.get_Parameter(BuiltInParameter.VIEW_DETAIL_LEVEL).Set(this.m_DetailLevel);
					transaction.Commit();
					elementId = view3D.Id;
					text = view3D.Name;
					break;
				}
			}
			if (null == elementId)
			{
				Transaction transaction2 = new Transaction(document2);
				transaction2.Start("shows ectionBox in the 3dView");
				XYZ direction = new XYZ(-1.0, 1.0, -1.0);
				View3D view3D2 = RevitVersionFuncs.NewView3D(document2, direction);
                view3D2.DisplayStyle = (DisplayStyle)8;
				view3D2.get_Parameter(BuiltInParameter.VIEW_DETAIL_LEVEL).Set(this.m_DetailLevel);
				text = view3D2.Name;
				transaction2.Commit();
				if (view3D2 == null)
				{
					document2.Close(false);
					return false;
				}
				elementId = view3D2.Id;
			}
			List<ElementId> list = new List<ElementId>();
			list.Add(elementId);
			string tempPath = Path.GetTempPath();
			string text2 = "temp";
			string filePath = tempPath + text2 + ".jpg";
			this.m_Option.FilePath = filePath;
			this.m_Option.SetViewsAndSheets(list);
			try
			{
				document2.ExportImage(this.m_Option);
			}
			catch (Exception)
			{
			}
			string text3 = "三维视图";
			string text4 = string.Concat(new string[]
			{
				tempPath,
				text2,
				" - ",
				text3,
				" - ",
				text,
				".jpg"
			});
			if (!File.Exists(text4))
			{
				text3 = "3D View";
				text4 = string.Concat(new string[]
				{
					tempPath,
					text2,
					" - ",
					text3,
					" - ",
					text,
					".jpg"
				});
			}
			string text5 = tempPath + "Preview.jpg";
			this.ChangeJPGSize(text4, text5);
			Image.GetThumbnailImageAbort callback = new Image.GetThumbnailImageAbort(this.ThumbnailCallback);
			Image image = Image.FromFile(text5);
			pbx.Image = (image.GetThumbnailImage(200, 200, callback, IntPtr.Zero).Clone() as Image);
			image.Dispose();
			try
			{
				File.Delete(text4);
				File.Delete(text5);
			}
			catch (Exception ex)
			{
				YJKMessageBox.Show(ex.Message);
			}
			uiApp.OpenAndActivateDocument(document.PathName);
			return true;
		}

		public bool ThumbnailCallback()
		{
			return false;
		}

		private void ChangeJPGSize(string imagePath, string exportFileFillPath)
		{
			Image image = Image.FromFile(imagePath);
			int num = ((Bitmap)image).Width;
			int num2 = ((Bitmap)image).Height;
			Bitmap bitmap = new Bitmap((Bitmap)image, num, num2);
			int width = bitmap.Width;
			int height = bitmap.Height;
			if (num2 > num)
			{
				num = num2;
			}
			else if (num > num2)
			{
				num2 = num;
			}
			float horizontalResolution = bitmap.HorizontalResolution;
			float verticalResolution = bitmap.VerticalResolution;
			float xDpi = 200f;
			float yDpi = 200f;
			try
			{
				Bitmap bitmap2 = new Bitmap(num, num2);
				Graphics graphics = Graphics.FromImage(bitmap2);
				SolidBrush brush = new SolidBrush(System.Drawing.Color.White);
				graphics.FillRectangle(brush, 0, 0, num, num2);
				int x = (int)((double)(num - width) / 2.0);
				int y = (int)((double)(num2 - height) / 2.0);
				graphics.DrawImage(bitmap, x, y, width, height);
				bitmap2.SetResolution(xDpi, yDpi);
				bitmap2.Save(exportFileFillPath, ImageFormat.Jpeg);
				bitmap2.Dispose();
				image.Dispose();
			}
			catch (Exception)
			{
				image.Dispose();
			}
		}

		private Image GetImg(string strPhoto, int width, int height)
		{
			Image thumbnailImage = new Bitmap(strPhoto).GetThumbnailImage(width, height, null, (IntPtr)0);
			Graphics graphics = Graphics.FromImage(thumbnailImage);
			graphics.DrawImage(thumbnailImage, width, height, thumbnailImage.Width, thumbnailImage.Height);
			graphics.Dispose();
			Image result = thumbnailImage.Clone() as Image;
			thumbnailImage.Dispose();
			return result;
		}

		private void readFamilyFile()
		{
		}

		private void btnCancel_Click(object sender, EventArgs e)
		{
			base.Close();
		}

		public static DlgAddStandardRoom GetInstance(DlgMain main)
		{
			if (DlgAddStandardRoom.daf == null || DlgAddStandardRoom.daf.IsDisposed)
			{
				DlgAddStandardRoom.daf = new DlgAddStandardRoom(main);
				DlgAddStandardRoom.daf.MdiParent = main.ActiveMdiChild;
			}
			return DlgAddStandardRoom.daf;
		}

		private void tbxName_TextChanged(object sender, EventArgs e)
		{
		}

		private void tbxName_KeyPress(object sender, KeyPressEventArgs e)
		{
			if (e.KeyChar != '~' || e.KeyChar != '!' || e.KeyChar != '@' || e.KeyChar != '#' || e.KeyChar != '$' || e.KeyChar != '%' || e.KeyChar != '^' || e.KeyChar != '&' || e.KeyChar != '*' || e.KeyChar != '(' || e.KeyChar != ')' || e.KeyChar != '{' || e.KeyChar != '}' || e.KeyChar != '"' || e.KeyChar != '\'' || e.KeyChar != '|' || e.KeyChar != '\\' || e.KeyChar != ';' || e.KeyChar != ',' || e.KeyChar != '<' || e.KeyChar != '>' || e.KeyChar != '?' || e.KeyChar != '/')
			{
				e.Handled = true;
			}
		}

		private void DlgAddFamily_Load(object sender, EventArgs e)
		{
		}

		private void DlgAddStandardRoom_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Escape)
			{
				base.Close();
			}
		}

		private static DlgAddStandardRoom daf;

		private IDlgBase mForm;

		private OpenFileDialog ofd = new OpenFileDialog();

		private List<DirectoryInfo> directoryList = new List<DirectoryInfo>();

		private bool isMulti;

		private ImageExportOptions m_Option;

		private int m_DetailLevel = 3;

		private DataGridViewDisableCheckBoxColumn dataGridViewDisableCheckBoxColumn1;
	}
}
